package com.ljx.funchat.common.aspect.frequency;

import com.google.common.collect.Maps;
import com.google.common.util.concurrent.RateLimiter;
import com.ljx.funchat.common.annotation.frequency.FrequencyControl;
import com.ljx.funchat.common.exception.BusinessException;
import com.ljx.funchat.common.exception.CommonErrorEnum;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Map;

@Slf4j
@Aspect
@Component
public class FrequencyControlAspect {

    /**
     * 不同的接口，不同的流量控制
     * map的key为 FrequencyControl.key
     */
    private final Map<String, RateLimiter> limitMap = Maps.newConcurrentMap();

    @Around("@annotation(com.ljx.funchat.common.annotation.frequency.FrequencyControl)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        // 频控注解
        FrequencyControl frequencyControl = method.getAnnotation(FrequencyControl.class);
        if (frequencyControl != null) {
            //key作用：不同的接口，不同的流量控制
            String key= frequencyControl.key();
            RateLimiter rateLimiter = null;
            if (!limitMap.containsKey(key)){
                rateLimiter = RateLimiter.create(frequencyControl.count());
                limitMap.put(key, rateLimiter);
                log.info("新建了令牌桶={}，容量={}", key, frequencyControl.count());
            }
            rateLimiter = limitMap.get(key);
            // 拿令牌
            boolean acquire = rateLimiter.tryAcquire(frequencyControl.time(), frequencyControl.unit());
            // 拿不到命令，直接返回异常提示
            if (!acquire) {
                log.error("令牌桶={}，获取令牌失败", key);
                throw new BusinessException(CommonErrorEnum.LOCK_LIMIT);
            }
        }
        return joinPoint.proceed();
    }
}
